import { Router } from 'express';
import { db } from '../utils/db.js';
import { requireAuth, requireRole } from '../utils/auth.js';

const router = Router();

router.get('/', requireAuth, (req, res) => {
  const tenders = db
    .prepare(
      `SELECT t.*, u.company_name AS created_by_company
       FROM tenders t JOIN users u ON u.id = t.created_by
       ORDER BY t.created_at DESC`
    )
    .all();
  if (req.accepts('html')) {
    return res.render('tenders', { tenders, title: '招标信息' });
  }
  return res.json(tenders);
});

router.get('/new', requireRole('TENDERER'), (req, res) => {
  res.render('tender_form', { tender: null, error: null, title: '发布招标' });
});

router.post('/', requireRole('TENDERER'), (req, res) => {
  const { tender_code, drug_name, manufacturer, package_req, total_quantity, deadline, deposit_amount } = req.body;
  try {
    db.prepare(
      `INSERT INTO tenders (tender_code, drug_name, manufacturer, package_req, total_quantity, deadline, deposit_amount, created_by)
       VALUES (?,?,?,?,?,?,?,?)`
    ).run(
      tender_code,
      drug_name,
      manufacturer,
      package_req || null,
      Number(total_quantity),
      deadline,
      Number(deposit_amount),
      req.session.user.id
    );
    res.redirect('/tenders');
  } catch (err) {
    res.status(400).render('tender_form', { tender: null, error: err.message, title: '发布招标' });
  }
});

router.get('/:id/edit', requireAuth, (req, res) => {
  const tender = db.prepare('SELECT * FROM tenders WHERE id = ?').get(req.params.id);
  if (!tender) {
    return res.status(404).render('error', { message: '未找到招标信息' });
  }
  if (!(req.session.user.role === 'ADMIN' || tender.created_by === req.session.user.id)) {
    return res.status(403).render('error', { message: '无权编辑该招标信息' });
  }
  res.render('tender_form', { tender, error: null, title: '编辑招标' });
});

router.post('/:id', requireAuth, (req, res) => {
  const tender = db.prepare('SELECT * FROM tenders WHERE id = ?').get(req.params.id);
  if (!tender) {
    return res.status(404).render('error', { message: '未找到招标信息' });
  }
  if (!(req.session.user.role === 'ADMIN' || tender.created_by === req.session.user.id)) {
    return res.status(403).render('error', { message: '无权更新该招标信息' });
  }
  const { tender_code, drug_name, manufacturer, package_req, total_quantity, deadline, deposit_amount } = req.body;
  try {
    db.prepare(
      `UPDATE tenders
       SET tender_code=?, drug_name=?, manufacturer=?, package_req=?, total_quantity=?, deadline=?, deposit_amount=?, updated_at=datetime('now')
       WHERE id=?`
    ).run(
      tender_code,
      drug_name,
      manufacturer,
      package_req || null,
      Number(total_quantity),
      deadline,
      Number(deposit_amount),
      req.params.id
    );
    res.redirect('/tenders');
  } catch (err) {
    res
      .status(400)
      .render('tender_form', { tender: { ...tender, ...req.body }, error: err.message, title: '编辑招标' });
  }
});

export default router;


